import {Component} from 'react';
import App from 'layout/App.js'
import CommonModal from './../../components/CommonModal/index.jsx';
import {Breadcrumb, Button, Checkbox, Notification, Select, Table} from 'tinper-bee';
import {
    deleteWorkGanttItem,
    getExportProjectPlan,
    getUserBaseDataUrl,
    getWorkGanttProgress,
    getWorkGanttTable,
    onCheckApprovePerm,
    onSearchHistoryList,
    onSubmitPlan,
    onWorkflowApprove,
    onWorkflowReject
} from './workgantt.config.js';
import {vendorsDanger, vendorsFmtDate, vendorsGetUrlParam} from 'utils/config.js';
import './index.less';
import Affix from 'bee-affix';
import moment from 'moment';
import Tooltip from 'bee-tooltip';
import 'bee-tooltip/build/Tooltip.css';
import TargetModal from "./TargetModal.jsx";
import exportExcel from '../../utils/exportExcel.js';
import Gantt from '../../components/Gantt/index.js';

const Option = Select.Option;
moment.locale('zh-cn');
let loopData = null;
let Flag = true;
let isCanSubmitPlan = true;

const textOverflowIndex = 10; // 控制项目名称在多少个字符后隐藏

const notification = Notification.newInstance({ position: 'bottomRight' });

let tenantId;
let cookieStr = document.cookie.split(';').find(cur => cur.indexOf('tenantid=') != -1)
if (cookieStr) {
	tenantId = cookieStr.split('=')[1];
}

@TargetModal()
export default class WorkGantt extends Component {
	constructor(props) {
		super(props);
		this.state = {
			projectList: [],
			projectKey: '',
			tableData :[],
			projectItemArray: [],
			projectTotalProgress: 0,
			showModal: false,
			chooseItemData: null,
			defaultSelectKey: '',
			downloadStatus: false,
			modalSize: 'sm',
			modalTitle: '',
			modalStatus: '',
			paramBtnContext: null,
			modalConfirmStatus: null,
			modalCancelStatus: null,
			opnionText: '',
			modalOneBtnStatus: false,
			assignPersonData: {},
			oneButtonText: '',
			checked: false,
			initAssign: null,
			isFromB: false,
			userName: '',
			paramBtnClass: null,
			submitStatus: true,
			historyListData: [],
			initSetFlag: false,
			showBreadFlag: false,
			expanded : false, 
			expandRecord : null,
		}
	}
	componentDidMount() {
		this.init();
		this.getUserBaseData();
		sessionStorage.setItem('toAdjust', false);


		let fromGroupData = JSON.parse(sessionStorage.getItem('fromGroupData'));
		if (fromGroupData) {
			let urlParamArr = Object.keys(fromGroupData);
			let startPage = vendorsGetUrlParam(decodeURI(window.location.href));
			startPage = Object.keys(startPage);
			if (urlParamArr && urlParamArr.length && startPage && startPage.length) {
				this.setState({
					showBreadFlag: true
				})
			}
		}
	}
	init = () => {
		// 获取项目列表数据
		getWorkGanttProgress({},
			res => {
		
				let data = res.data.result.objects;
				let isHasDefaultKey = sessionStorage.getItem('ganttKey');
				let bPkProject = sessionStorage.getItem('bPkProject');
				let bProjectName = sessionStorage.getItem('bProjectName');

				// 处理页面不关闭情况下 切换租户残留原有pkProject问题
				let keyForData = [];
				data.forEach((item, index) => {
					keyForData.push(item.pkProject);
				})
				if (!keyForData.includes(isHasDefaultKey)) {
					isHasDefaultKey = undefined;
				}

				if (data.length !== 0) {
					if (bPkProject && bPkProject !== 'undefined') {
						let data = [];
						data.push({ pkProject: bPkProject, sname: bProjectName });
						this.setState({
							projectList: data,
							defaultSelectKey: bPkProject,
							isFromB: true,
							initSetFlag: false
						}, () => {
							this.handleSelectChange(this.state.defaultSelectKey);
							// 跨页面存储当前选择的项目id
							// sessionStorage.setItem('ganttKey', bPkProject);
							sessionStorage.setItem('bPkProject', undefined);
							sessionStorage.setItem('bProjectName', undefined);
						});
					} else {
						if (isHasDefaultKey) {
							this.setState({
								projectList: data,
								defaultSelectKey: isHasDefaultKey,
								initSetFlag: true
							}, () => {
								this.handleSelectChange(this.state.defaultSelectKey);
								// 跨页面存储当前选择的项目id
								// sessionStorage.setItem('ganttKey', isHasDefaultKey);
							});
						} else {
							this.setState({
								projectList: data,
								defaultSelectKey: data[0].pkProject,
								initSetFlag: true
							}, () => {
								this.handleSelectChange(this.state.defaultSelectKey);
								// 跨页面存储当前选择的项目id
								//sessionStorage.setItem('ganttKey', data[0].pkProject);
							});
						}
					}
				} else {
					this.setState({
						projectList: data
					});
				}
			},
			error => { }
		)
	}
	handleSelectChange = (value) => {
		let divNode = document.getElementsByClassName('u-select-selection-selected-value')[0]; // 清空下拉框的鼠标hover时候的title值
        setTimeout(() => {
            divNode.setAttribute("title", "");
        }, 500);
		let itemTotalDay = 0;
		let itemTotalPresent = 0;
		let itemCurrentPresent = 0;
		// 跨页面存储当前选择的项目id
		if (this.state.initSetFlag) {
			sessionStorage.setItem('ganttKey', value);
		}
		// 获取对应的项目进度数据
		getWorkGanttTable({ pkProject: value, ieStamp: new Date().getTime() },//projectId
			res => {
				let data = res.data.result === null ? [] : res.data.result;
				// 计算每项独立数据的进度
				loopData = data;
			
				//优化后，后台处理了，不适应这个算法了
				// this.findMinIndexItem(loopData);
				//汇总计算出总进度
				data.forEach((item, index) => {
					itemTotalDay += parseInt(item.planDays);
					itemTotalPresent += parseInt(item.progress) * parseInt(item.planDays);
				})
				// 存在提交失败信息，提示用户
				data.map((item) => {
					let message = item['failedCommit'];
					if (message) {
						notification.notice({
							content: <span>{message}</span>,
							duration: 3,
							color: 'dangerlight',
							closable: true,
						});
					}
				});
				itemCurrentPresent = Math.round(itemTotalPresent / itemTotalDay);
				if (isNaN(itemCurrentPresent)) {
					itemCurrentPresent = 0;
				}

				this.setState({
					tableData: data,
					projectItemArray: new Array(data.length),
					projectTotalProgress: itemCurrentPresent,
					projectKey: value,
					defaultSelectKey: value
				});
			},
			error => { }
		)
	}
	
	// findMinIndexItem = (arr) => {
	// 	arr.forEach((item, index) => {
	// 		// if (item.childCount !== 0) {
	// 		// 	this.findMinIndexItem(item.children);
	// 		if (item.children && item.children.length !== 0 || item.scheduleItemVOS && item.scheduleItemVOS.length !== 0) {
	// 			let data = item.children && item.children.length !== 0 ? item.children : item.scheduleItemVOS
	// 			this.findMinIndexItem(data);
	// 		} else {
	// 			if (item.pkSchedule !== item.pkRoot) {//pkPlan
	// 				// 找到最末级并去计算父级的正确progress进度值
	// 				this.computedMinIndexParentItem(arr, item);
	// 			}
	// 		}
	// 	})
	// }
	
	// computedMinIndexParentItem = (arr, propsItem) => {
	// 	let totalDay = 0;
	// 	let totalPresent = 0;
	// 	let currentPresent = 0;
	// 	let tableData = loopData;
	// 	for (let i = 0; i < arr.length; i++) {
	// 		let step = 0;
	// 		totalDay += parseInt(arr[i].planDays);
	// 	//	totalPresent += parseInt(arr[i].progress) * parseInt(arr[i].planDays);
	// 	totalPresent += parseInt(arr[i].progressVO.progress) * parseInt(arr[i].planDays);
	// 	}
	// 	currentPresent = Math.round(totalPresent / totalDay);

	// 	// 在树状数据里面找到对应的父级并赋值
	// 	this.recursionDataForParent(tableData, currentPresent, propsItem);

	// }

	// recursionDataForParent = (tableData, currentPresent, propsItem) => {
	// 	let tableDataAll = loopData;
	// 	tableData.forEach((item) => {
	// 		if (item.pkSchedule === propsItem.pkParent) {//pkPlan
	// 			item['progress'] = currentPresent;
	// 			//item[''] = currentPresent;
	// 			// item 为父级 需要往上去递归遍历所以父级
	// 			if (item.pkParent !== null) {
	// 				this.findParentItem(tableDataAll, item);
	// 			}
	// 		} else {
	// 			//if (item.children !== null) {
	// 			if (item.children && item.children.length !== 0 || item.scheduleItemVOS && item.scheduleItemVOS.length !== 0) {
	// 				let data = item.children && item.children.length !== 0 ? item.children : item.scheduleItemVOS
	// 				this.recursionDataForParent(data, currentPresent, propsItem);
	// 			}
	// 		}
	// 	})
	// }
	// findParentItem = (data, propsItem) => {
	// 	data.forEach((item) => {
	// 		if (item.pkSchedule === propsItem.pkParent) {//pkPlan
	// 			let data = item.children && item.children.length !== 0 ? item.children : item.scheduleItemVOS
	// 			this.computedMinIndexParentItem(data, propsItem);
	// 		} else {
	// 			//if (item.children !== null) {
	// 			if (item.children && item.children.length !== 0 || item.scheduleItemVOS && item.scheduleItemVOS.length !== 0) {
	// 				let data = item.children && item.children.length !== 0 ? item.children : item.scheduleItemVOS
	// 				this.findParentItem(data, propsItem);
	// 			}
	// 		}
	// 	})
	// }
	handlerToCreatePage = () => {
		let projectKey = this.state.projectKey;
		let projectList = this.state.projectList;
		let projectObj = null;
		projectList.forEach((item, index) => {
			if (item.pkProject === projectKey) {
				projectObj = item;
			}
		})
		if (projectObj && projectObj.projectState === 1) {
			vendorsDanger({ text: '项目已经结束，不可操作！' });
			return;
			
		}
		if (this.state.defaultSelectKey !== '') {
			window.location.href = './workganttadd.html';
		}
	}

	// 导出进度简报
	exportProcess = () => {
		getExportProjectPlan({projectId: this.state.projectKey}).then((res) => {
			let {exMsg, resultCode} = res.data;
			if(resultCode === "busi_ex") {
				vendorsDanger({text: exMsg});
			} else {
				exportExcel(res.data, '项目进度简报');
			}
		});
	}

	handlerToEditPage = (item) => {
		if (item.creator !== this.state.userName) {
			vendorsDanger({ text: '用户没有该单据的调整权限，请刷新后重试！' });
			return;
		}
		if (item.projectState === 1) {
			vendorsDanger({ text: '项目已经结束，不可操作！' });
			return;
		}
		// window.location.href = '';
		// 跨页面存储当前选择的项目pkPlan
		sessionStorage.setItem('ganttRootId', item.pkSchedule);//pkPlan
		sessionStorage.setItem('ganttRootTime', item.creationtime);
		sessionStorage.setItem('ganttRootUserName', item.creatorName);
		window.location.href = './workganttedit.html';
	}
	handlerDeleteItem = (item) => {
		if (item.creator !== this.state.userName) {
			vendorsDanger({ text: '用户没有该单据的调整权限，请刷新后重试！' });
			return;
		}
		if (item.projectState === 1) {
			vendorsDanger({ text: '项目已经结束，不可操作！' });
			return;
		}
		this.setState({
			showModal: true,
			chooseItemData: item,
			modalSize: 'sm',
			modalTitle: '',
			modalStatus: 'delete',
			paramBtnContext: null,
			modalConfirmStatus: this.handlerDeleteConfirm,
			modalCancelStatus: this.handlerDeleteClose,
			modalOneBtnStatus: false,
			paramBtnClass: null
		});
	}
	onhide = () => {
		this.setState({
			showModal: false
		});
	}
	handlerDeleteConfirm = () => {
		deleteWorkGanttItem({
		//	pkPlan: this.state.chooseItemData.pkPlan,
		pkSchedule: this.state.chooseItemData.pkSchedule,
			changeFlag: this.state.chooseItemData.changeFlag
		},
			res => {
				let data = res.data;
				if (data.resultCode === 'ok') {
					this.handleSelectChange(this.state.projectKey);
					this.setState({
						showModal: false
					});
				} else {
					vendorsDanger({ text: data.exMsg });
				}
			},
			error => {

			});
	}
	handlerDeleteClose = () => {
		this.setState({
			showModal: false
		});
	}
	handlerShowItem = index => {
		this.state.projectItemArray[index] = !this.state.projectItemArray[index];
		this.setState({
			projectItemArray: this.state.projectItemArray,

		});
	}
	getColumns = () => {
		let _me = this;
		return [
			{
				title: "计划名称",
				dataIndex: "name",
				key: "name",
				width: '15%',
				render(text, rec, index) {
					return <p className="clearfix">
						<span>{rec.code}</span>
						<a href="javascript:;" title={text}>
							{text}
						</a>
					</p>
				}
			},
			{
				title: "工期",
				dataIndex: "planDays",
				key: "planDays",
				className: "plan-table-text-center",
				width: "5%"
			},
			{
				title: "计划开始日期",
				dataIndex: "planStartDate",
				key: "planStartDate",
				className: "plan-table-text-center",
				width: '8%',
				render(text, rec, index) {
					return <a href="javascript:;">{vendorsFmtDate(text)}</a>
				}
			},
			{
				title: "计划完成日期",
				dataIndex: "planEndDate",
				key: "planEndDate",
				className: "plan-table-text-center",
				width: '8%',
				render(text, rec, index) {
					return <a href="javascript:;">{vendorsFmtDate(text)}</a>
				}
			},
			{
				title: "前置计划",
				dataIndex: "dependPlanName",
				key: "dependPlanName",
				className: "plan-table-text-center",
				width: "5%"
			},
			{
				title: "责任部门",
				dataIndex: "departmentName",
				className: "plan-table-text-center",
				key: "departmentName",
				width: "5%"
			},
			{
				title: "负责人",
				dataIndex: "managerName",
				className: "plan-table-text-center",
				key: "managerName",
				width: '5%',
			},
			{
				title: "里程碑",
				className: "plan-table-text-center milestone-name-style",
				width: '18%',
				children: [
					{
					  title: "里程碑档案",
					  dataIndex: "milestoneName",
					  key: "milestoneName",
					  className: "plan-table-text-center",
					  width: '9%',
					  render(text, rec, index) {
						return (
						<span>{text}</span>
						)
					  }
					},
					{
					  title: "里程碑单据",
					  dataIndex: "relatedBillTypeName",
					  key: "relatedBillTypeName",
					  className: "plan-table-text-center",
					  width: '9%',
					  render(text, rec, index) {
						  return (
						  <span>{text}</span>
						  )
					  }
					}
				  ]
			},
			{
				title: "指标",
				dataIndex: "indexNumber",
				className: "plan-table-text-center",
				key: "indexNumber",
				width: "4%",
				render (text, rec, index) {
					return <a href="javascript:;" onClick={()=>_me.handlerChooseTarget(text, rec, index)} className = {"addTarget"}>
						{rec.childCount === 0 ?text : text? text : ""}
					</a>
				}
			},
			{
				title: "进度",
				dataIndex:"progressVO.progress",// "progress",
				key: "progressVO.progress",// "progress",
				className: "plan-table-text-center",
				width: "5%",
				render(text, rec, index) {
					return <a href="javascript:;">{text + '%'}</a>
				}
			},
			{
				title: "实际开始日期",
				dataIndex: "progressVO.startDate",
				key: "progressVO.startDate",
				width: '8%',
				className: "plan-table-text-center",
				render(text, rec, index) {
					return <a href="javascript:;">{vendorsFmtDate(text)}</a>
				}
			},
			{
				title: "实际完成日期",
				dataIndex: "progressVO.endDate",
				key: "progressVO.endDate",
				width: '7%',
				className: "plan-table-text-center",
				render(text, rec, index) {

					if (rec.progressVO.progress === 100) {
						return <a href="javascript:;">{vendorsFmtDate(text)}</a>
					} else {
						''
					}
				}
			},
			{
				title: "完成人",
				dataIndex: "planFinisherName",
				key: "planFinisherName",
				width: '7%',
				className: "plan-table-text-center",
				render(text, rec, index) {
					return(
						<span>{text}</span>
					)
				}
			}
		]
	}
	handlerChooseTarget = (text, record, index)=>{
		if(text){
			this.props.setCurStateByWrapCom({
				showModal : true,
				from :'browse',
				pkPlan : record.pkScheduleItem//record.pkPlan
			})//打开指标列表的模态框
		}
	}

	handlerShowDownload = () => {
		this.setState({
			downloadStatus: true
		});
	}
	handlerHideDownload = () => {
		this.setState({
			downloadStatus: false
		});
	}
	handlerComputedBillStatus = (type) => {
		let billStatusText = '';
		switch (type) {
			case 0:
				billStatusText = '未提交';
			case 5:
				billStatusText = '自由态';
				break;
			case 7:
				billStatusText = '审批中';
				break;
			case 8:
				billStatusText = '已驳回';
				break;
			case 9:
				billStatusText = '审批通过';
				break;
		}
		return billStatusText
	}
	handlerGoPlanHistoryPage = (item) => {
		sessionStorage.setItem('GanntPkproject', item.pkProject);
		sessionStorage.setItem('GanntPkplan', item.pkOriginal);//pkPlan
		window.location = './planapproval.html';
	}
	handlerConfirmChooseApporea = () => {
		let assignPersonData = this.state.assignPersonData;
		let isChooseItemFlag = false;
		let paramArray = [];
		let param = null;
		assignPersonData.forEach((item, index) => {
			if (item.isChecked) {
				paramArray.push(item);
				isChooseItemFlag = true;
			}
		})
		if (this.state.submitStatus) {
			if (isChooseItemFlag) {
				this.state.initAssign.assignInfo.assignInfo.assignInfoItems[0].participants = paramArray;
			}
			onSubmitPlan(this.state.initAssign,
				res => {
					if (res.data.resultCode !== 'busi_ex') {
						this.init();
						this.setState({
							showModal: false
						});
					} else {
						vendorsDanger({ text: res.data.exMsg });
					}
				},
				error => { }
			);
		} else {
			this.state.initAssign.assignInfoItems[0].participants = paramArray;
			this.handlerFlowApprove();
		}
	}
	handlerSubmitPlan = (item, index) => {
		if (isCanSubmitPlan) {
			isCanSubmitPlan = false;
		} else {
			return;
		}
		if (item.creator !== this.state.userName) {
			vendorsDanger({ text: '用户没有该单据的调整权限，请刷新后重试！' });
			return;
		}
		if (item.projectState === 1) {
			vendorsDanger({ text: '项目已经结束，不可操作！' });
			return;
		}
		//onSubmitPlan({ pkSchedule: item.pkSchedule, billType: 'JDJH', pkProject: item.pkProject },//pkPlan: item.pkPlan,
		onSubmitPlan({...item},//pkPlan: item.pkPlan,
			res => {
				// 前端手动更新提交状态，等二次查询列表再次刷新页面
				let data = res.data.result;

				let tableData = this.state.tableData;
				tableData[index] = data;
				this.setState({
					tableData
				});
				if (res.data.resultCode === 'ok') {
					if (data.assignInfo !== null && data.assignInfo.assignInfo.assignInfoItems[0].participants.length !== 1) {
						this.setState({
							showModal: true,
							modalSize: 'lg',
							modalTitle: '选择审批人',
							modalStatus: 'approvalPerson',
							modalConfirmStatus: this.handlerConfirmChooseApporea,
							modalOneBtnStatus: true,
							chooseItemData: item,
							oneButtonText: '确定',
							assignPersonData: data.assignInfo.assignInfo.assignInfoItems[0].participants,
							initAssign: data,
							paramBtnClass: null
						});
					} else if (data.assignInfo !== null && data.assignInfo.assignInfo.assignInfoItems[0].participants.length === 1) {
						this.setState({
							showModal: false,
							modalSize: 'lg',
							modalTitle: '选择审批人',
							modalStatus: 'approvalPerson',
							modalConfirmStatus: this.handlerConfirmChooseApporea,
							modalOneBtnStatus: true,
							chooseItemData: item,
							oneButtonText: '确定',
							assignPersonData: data.assignInfo.assignInfo.assignInfoItems[0].participants,
							initAssign: data,
							paramBtnClass: null
						});
						this.handlerConfirmChooseApporea();
					} else {
						this.init();
					}
					isCanSubmitPlan = true;
				} else {
					isCanSubmitPlan = true;
					vendorsDanger({ text: res.data.exMsg });
				}
			},
			error => { }
		)
	}
	handlerAdjustPlan = (item) => {
		if (item.creator !== this.state.userName) {
			vendorsDanger({ text: '用户没有该单据的调整权限，请刷新后重试！' });
			return;
		}
		if (item.projectState === 1) {
			vendorsDanger({ text: '项目已经结束，不可操作！' });
			return;
		}
		sessionStorage.setItem('toAdjust', true);
		sessionStorage.setItem('ganttRootId', item.pkSchedule);//item.pkPlan
		sessionStorage.setItem('ganttRootTime', item.creationtime);
		sessionStorage.setItem('ganttRootUserName', item.creatorName);
		window.location.href = './workganttedit.html';
	}
	handlerWorkflowApprove = (item, index) => {
		if (item.projectState === 1) {
			vendorsDanger({ text: '项目已经结束，不可操作！' });
			return;
		}
		onCheckApprovePerm({ pkBill: item.pkSchedule },//item.pkPlan
			res => {
				if (res.data.resultCode === 'ok') {
					if (res.data.result) {
						this.setState({
							showModal: true,
							modalSize: 'lg',
							modalTitle: '审批意见',
							modalStatus: 'approvalOpinion',
							paramBtnContext: { 'type-1': '驳回', 'type-2': '通过' },
							modalConfirmStatus: () => {this.handlerFlowApprove(item, index)},
							modalCancelStatus: this.handlerflowReject,
							chooseItemData: item,
							modalOneBtnStatus: false,
							paramBtnClass: null,
							opnionText: ''
						});
					} else {
						vendorsDanger({ text: '用户没有该单据的审批权限，请刷新后重试！' });
					}
				}
			},
			error => { }
		);
	}
	handlerFlowApprove = (item, index) => {
		onWorkflowApprove({
			pkBill: this.state.chooseItemData.pkSchedule,//pkPlan
			billType: 'JDJH',
			tenantId: this.state.chooseItemData.pkTenant,
			opinion: this.state.opnionText,
			assignFlag: this.state.submitStatus ? false : true,
			assignInfo: this.state.submitStatus ? null : this.state.initAssign
		},
			res => {
				if (res.data.resultCode !== 'busi_ex') {
					if (res.data.result !== null) {
						let data = res.data.result;
						if (this.state.submitStatus) {
							if (data === 'success') {
								this.setState({
									showModal: false,
									submitStatus: true,
									opnionText: ''
								});
								// 前端手动更新审批后的状态
								// item.billstatus = 1;前端手动处理的，但不知处理什么问题。
								item.billstatus = 9;//不知是什么原因，那也手动更新审批后的状态吧。
								this.state.tableData[index] = item;
								this.setState({ tableData: this.state.tableData });
							} else if (data.assignInfoItems[0].participants.length === 1) {
								onWorkflowApprove({
									pkBill: this.state.chooseItemData.pkSchedule,//pkPlan
									billType: 'JDJH',
									tenantId: this.state.chooseItemData.pkTenant,
									opinion: this.state.opnionText,
									assignFlag: true,
									assignInfo: data
								},
									res => {
										if (res.data.resultCode !== 'busi_ex') {
											this.init();
											this.setState({
												showModal: false
											});
										} else {
											vendorsDanger({ text: res.data.exMsg });
										}
									}, error => {
									})
							} else {
								this.setState({
									showModal: true,
									modalSize: 'lg',
									modalTitle: '选择审批人',
									modalStatus: 'approvalPerson',
									modalConfirmStatus: this.handlerConfirmChooseApporea,
									modalOneBtnStatus: true,
									oneButtonText: '确定',
									assignPersonData: data.assignInfoItems[0].participants,
									initAssign: data,
									paramBtnClass: null,
									submitStatus: false,
									opnionText: ''
								});
							}
						} else {
							this.setState({
								showModal: false,
								modalSize: 'lg',
								modalTitle: '选择审批人',
								modalStatus: 'approvalPerson',
								modalConfirmStatus: this.handlerConfirmChooseApporea,
								modalOneBtnStatus: true,
								oneButtonText: '确定',
								paramBtnClass: null,
								submitStatus: true,
								opnionText: ''
							});
						}
					}
				} else {
					vendorsDanger({ text: res.data.exMsg });
					this.setState({
						showModal: false
					});
				}
			},
			error => { }
		)
	}
	handlerflowReject = () => {////pkPlan
		onWorkflowReject({ pkBill: this.state.chooseItemData.pkSchedule, billType: 'JDJH', tenantId: this.state.chooseItemData.pkTenant, opinion: this.state.opnionText, assignFlag: false },
			res => {
				if (res.data.resultCode !== 'busi_ex') {
					this.init();
					this.setState({
						showModal: false,
						opnionText: ''
					});
				} else {
					vendorsDanger({ text: res.data.exMsg });
				}
			},
			error => { })
	}
	handlerSaveOpnionText = (e) => {
		let value = e.target.value;
		this.setState({
			opnionText: value
		});
	}
	changeCheck = (index) => {
		let assignPersonData = this.state.assignPersonData;
		assignPersonData[index].isChecked = !assignPersonData[index].isChecked;
		this.setState({
			assignPersonData
		});
	}
	getModalContext = (type) => {
		let modalText = '';
		switch (type) {
			case 'delete':
				modalText = '是否删除该信息？';
				break;
			case 'approvalOpinion':
				modalText = <div>
					<textarea className="opinion--box" onChange={this.handlerSaveOpnionText}></textarea>
				</div>;
				break;
			case 'approvalPerson':
				modalText = <div className="approval--person">
					<p className="approval--title">审批成员(多选)</p>
					<ul className="approval--list">
						{this.state.assignPersonData.map((item, index) => {
							return <li key={item.id}>
								<Checkbox checked={item.isChecked} onChange={() => this.changeCheck(index)}></Checkbox>
								{item.name}
							</li>
						})}
					</ul>
				</div>;
				break;
			case 'approvalWay':
				modalText = <div className="approval--way">
					<div className="way--list">
						<ul>
							{this.state.historyListData.map((item, index) => {
								return this.handlerCreateListItem(item)
							})}
						</ul>
					</div>
				</div>;
				break;
		}
		return modalText
	}
	handlerCreateListItem = (item) => {
		if (item.allApprovalPersonName.indexOf(';') === -1) {
			return (<li className="clearfix">
				<div className="item--status">
					<span>{item.approvalStatusDesc}</span>
					{this.handlerComputedClass(item)}
					<b className="line"></b>
				</div>
				<div className="item--content">
					<div className="base--data clearfix">
						<span className="name">{item.allApprovalPersonName}</span>
						<span className="date">{item.approvalRecordVOList[0].endTime}</span>
					</div>
					<p>审批意见：{item.approvalRecordVOList[0].approvalComment}</p>
				</div>
			</li>)
		} else {
			return (<li className="clearfix">
				<div className="item--status">
					<span>{item.approvalStatusDesc}</span>
					{this.handlerComputedClass(item)}
					<b className="line"></b>
				</div>
				<div className="item--content">
					<div className="base--data clearfix">
						<p className="name--spe">{item.allApprovalPersonName.split(';').join('  ')}</p>
					</div>
					<ul className="list--spe">
						{item.approvalRecordVOList.map((item, index) => {
							return <li>
								<div className="base--data clearfix">
									<span className="name">{item.approvalPersonName}</span>
									<span className="date">{item.endTime}</span>
								</div>
								<p>审批意见：{item.approvalComment}</p>
							</li>
						})}
					</ul>
				</div>
			</li>)
		}
	}
	handlerComputedClass = (item) => {
		let className = "";
		switch (item.approvalStatus) {
			case 'submit':
			case 'adopt':
				className = <em className="right--status"></em>;
				break;
			case 'reject':
				className = <em className='fail--status'></em>;
				break;
			case 'approvalPending':
				className = <em className="pending--status"></em>;
				break;

		}
		return className
	}
	handlerHistoryList = (item) => {////pkPlan
		onSearchHistoryList({ billType: 'JDJH', tenantId: item.pkTenant, userId: this.state.userName, businessKey: item.pkSchedule, ieStamp: new Date().getTime() },
			res => {
				if (res.data.resultCode !== 'busi_ex') {
					this.setState({
						showModal: true,
						modalSize: 'lg',
						modalTitle: '审批轨迹',
						modalStatus: 'approvalWay',
						modalConfirmStatus: this.handlerConfirmChooseApporea,
						modalOneBtnStatus: false,
						chooseItemData: item,
						oneButtonText: '确定',
						paramBtnClass: { 'type-1': 'hide', 'type-2': 'hide' },
						historyListData: res.data.result
					});
				} else {
					vendorsDanger({ 'text': res.data.exMsg });
				}
			},
			error => {

			}
		)
	}
	getUserBaseData = () => {
		let _me = this;
		getUserBaseDataUrl({ 'isAjax': 1, 'ieStamp': new Date().getTime() },
			res => {
				if (res.data.result !== null) {
					_me.setState({
						userName: res.data.result.userId
					});
				} else {
					_me.setState({
						userName: ''
					});
				}
			},
			error => { }
		)
	}
	render() {
		let { showBreadFlag, projectList, projectItemIndex, projectItemArray, projectTotalProgress, tableData, defaultSelectKey, downloadStatus } = this.state;
		return (
			<App>
				<CommonModal show={this.state.showModal}
					cancel={this.state.modalCancelStatus}
					confirm={this.state.modalConfirmStatus}
					hide={this.onhide}
					content={this.getModalContext(this.state.modalStatus)}
					backdrop={true}
					size={this.state.modalSize}
					title={this.state.modalTitle}
					paramBtnContext={this.state.paramBtnContext}
					oneButton={this.state.modalOneBtnStatus}
					oneButtonText={this.state.oneButtonText}
					paramBtnClass={this.state.paramBtnClass}
				>
				</CommonModal>

				<Affix>
					<div className="header">
						<div className="header__btn--context clearfix">
							<div className="project-select clearfix">
								{
									showBreadFlag ? <div className="brc-nav" style={{ float: 'left' }}>
										<Breadcrumb>
											<Breadcrumb.Item href="./groupquery.html?page_state=1">
												集团查看
											</Breadcrumb.Item>
											<Breadcrumb.Item href="./dataanalysis.html?page_state=1">
												企业看板
											</Breadcrumb.Item>
											<Breadcrumb.Item active>
												计划编制
											</Breadcrumb.Item>
										</Breadcrumb>
									</div> : null
								}

								<div className="clearfix" style={{ float: 'left' }}>
									<p className="project-title">项目名称</p>
									<Select
										showSearch
										size="lg"
										style={{ width: 200, marginRight: 6 }}
										onChange={this.handleSelectChange}
										optionFilterProp="name"
										placeholder={'请选择'}
										value={defaultSelectKey}
										notFoundContent="没有相关条目"
										disabled={projectList.length === 0 || this.state.isFromB ? true : false}>
										{
											projectList.map((item, index) => {
												let text = item.sname;
												let displayText = text.length > textOverflowIndex ? text.substr(0, textOverflowIndex) + "..." : text;
												return (
													<Option name= {item.sname} value={item.pkProject}>
														<Tooltip
															className={[text.length > textOverflowIndex ? "show" : "hidden"]}
															inverse
															placement="top"
															overlay={text}>
															<div>{displayText}</div>
														</Tooltip>
													</Option>
												)
											})
										}
									</Select>
								</div>
							</div>
        {
            tenantId === "ga6oqeyu" ?
        <
            Button
            colors = "primary"
            className = "project-create"
            onClick = {this.exportProcess} > 导出进度简报 </Button> : null}
							<Button colors="primary" className="project-create" onClick={this.handlerToCreatePage}>创建计划</Button>
							<Button colors="primary" className="project-download" onClick={this.handlerShowDownload}>
								下载模板
							</Button>
							{
								downloadStatus && <ul className="dropdown-download" onMouseLeave={this.handlerHideDownload}>
									<li>
										<a href="https://gysypicture1.oss-cn-beijing.aliyuncs.com/static/file/%E8%AE%A1%E5%88%92%E6%A0%87%E5%87%86%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF-Project%E6%96%87%E4%BB%B6%E6%A0%BC%E5%BC%8F.mpp" target="_blank">Project文件</a>
									</li>
									<li>
										<a href="https://gysypicture1.oss-cn-beijing.aliyuncs.com/static/file/%E8%AE%A1%E5%88%92%E6%A0%87%E5%87%86%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF-Excel%E6%96%87%E4%BB%B6%E6%A0%BC%E5%BC%8F.xlsx" target="_blank">Excel文件</a>
									</li>
								</ul>
							}
						</div>
						<div className="header__progress clearfix">
							<span className="project-totle">总进度：{projectTotalProgress}%</span>
						</div>
					</div>
				</Affix>
				<div className="project__contain">
					{
						tableData.map((item, index) => {
							return (<div className={`project-item project-item-${index}`}>
								<div className="project-item-header clearfix">
									<i className={projectItemArray[index] ? 'show-item' : 'close-item'} onClick={() => { this.handlerShowItem(index) }}></i>
									<p className="item-title">{index + 1}. {item.name}</p>
									<p className="versio--number" onClick={() => this.handlerGoPlanHistoryPage(item)}>版本号：{item.version}</p>
									<p className="versio--type">状态: {this.handlerComputedBillStatus(item.billstatus)}</p>
									{(item.billstatus === 0 || item.billstatus === 8 || item.billstatus === 5 ? true : false) && <div className="project--btn__group">
										<div className="project-item-btn">
											<b onClick={() => { this.handlerSubmitPlan(item, index) }}>提交</b>
											<b onClick={() => { this.handlerToEditPage(item) }}>编辑</b>
											<b onClick={() => { this.handlerDeleteItem(item) }}>删除</b>
										</div>
										{item.billstatus === 8 ? (<span className="history--list" onClick={() => this.handlerHistoryList(item)}></span>) : (<span className="history--list visibility--hide"></span>)}
									</div>}
									{item.billstatus === 9 && <div className="project--btn__group">
										<div className="project-item-btn">
											<b onClick={() => this.handlerAdjustPlan(item)}>调整</b>
										</div>
										<span className="history--list" onClick={() => this.handlerHistoryList(item)}></span>
									</div>}
									{item.billstatus === 7 && <div className="project--btn__group">
										<div className="project-item-btn">
											<a href="javascript:;" onClick={() => this.handlerWorkflowApprove(item, index)}>审批</a>
										</div>
										<span className="history--list" onClick={() => this.handlerHistoryList(item)}></span>
									</div>}
									<div className="project-item-date clearfix">
										<p className="current-progress">当前进度：{item.progress}%</p>
										<p className="plan-total">计划总工期：{item.planDays}天</p>
										{
											item.planStartDate !== null && <p className="plan-date">计划日期：{vendorsFmtDate(item.planStartDate)}至{vendorsFmtDate(item.planEndDate)}</p>
										}
										{
											item.startDate !== null && <p className="actual-date">实际日期：{vendorsFmtDate(item.startDate)}至{item.progress === 100 ? vendorsFmtDate(item.endDate) :''}</p>
										}
									</div>
								</div>
								{
									projectItemArray[index] && <div className="project-item-content">
										<div className={`project-table project-table-${index}`} style={{display:'flex', justifyContent:'space-between'}}>
											<Table 
												style={{width: "48%"}} 
												data={ item.scheduleItemVOS && item.scheduleItemVOS.length ? item.scheduleItemVOS :[]} 
												columns={this.getColumns()}
												onExpand = { (expanded, record)=>{
													this.setState({
														expanded, 
														expandRecord: record,
													})
												}}
											
											></Table>
											<Gantt  
												style={{width: "48%"}} 
												contentKey = {
													{
														mainId : 'pkSchedule' ,
														childId : 'pkScheduleItem' ,
														planStartDate : 'planStartDate' ,
														planEndDate : 'planEndDate' ,
														startDate : 'progressVO.startDate' ,
														endDate : 'progressVO.endDate' ,
														progress: 'progressVO.progress' ,
														planDays : 'planDays' ,
														completedStatus :'completedStatus',
														name :'name',
														code:'code',
														managerName:'managerName',
														dependPlans :'dependPlans',
														pkMilestone:'pkMilestone',
														pkParent :'pkParent',
														isDelay :'isDelay'
													}
												}
												classNameLeftEle = {`project-table-${index}`} 
												data = {item.scheduleItemVOS} 
												onExpand = {this.state.expanded}
												expandRecord = {this.state.expandRecord}
												index = {index}
											/>
										</div>
									</div>
								}
							</div>)
						})
					}
				</div>
			</App>
		)
	}
}